<?php
class registrationmanager extends MySQL_Connector {
	public $username;
	public $password;
	public $log;
	private $save_ip = false;
	private $db_column = "";

	public function __construct() {
		parent::__construct();
		$this -> log = new log();
	}

	public function __destruct() {
		parent::__destruct();
	}
	
	public function save_ip($db_column) {
		if(!empty($db_column))
		{
			$this->db_column = $db_column;
			$this->save_ip = true;
		}
		else
		{
			$this->log->add_log_entry(new log_entry("Falsche Angabe einer Spalte in der Datenbank!", "error"));
		}
	}

	public function register() {
		if($this->are_post_vars_valid()) {
			$this -> username = string::clean_var($_POST['bn'], $this->con);
			$this -> password = hash("sha256", string::clean_var($_POST['pw'], $this->con));
			$query = "SELECT * FROM user WHERE username='" . $this -> username . "'";
			$result = $this -> con -> query($query) OR die(mysql_error());
			if (mysqli_num_rows($result) == 0) {
				if($this->save_ip)
				{
					$query = "INSERT INTO user (username, password, state, rang, ".$this->db_column.") VALUES ('" . $this -> username . "', '" . $this -> password . "', 0, 'Benutzer', '".$_SERVER['REMOTE_ADDR']."')";
				}
				else
				{
					$query = "INSERT INTO user (username, password, state, rang, ip_adress) VALUES ('" . $this -> username . "', '" . $this -> password . "', 0, 'Benutzer', '0', '')";
				}
				if ($this -> con -> query($query)) {
					$this -> log -> add_log_entry(new log_entry("Sie wurden erfolgreich registriert!", "success"));
				} else {
					$this -> log -> add_log_entry(new log_entry("Fehler beim Registrieren!<br />".$this->con->error, "error"));
				}
			} else {
				$this -> log -> add_log_entry(new log_entry("Ein Benuter mit dem Namen \"" . $this -> username . "\" existiert bereits.", "error"));
			}
		}
	}
	
	private function are_post_vars_valid()
	{
		$vars_valid = true;
		if(empty($_POST['bn']))
		{
			$this->log->add_log_entry(new log_entry("Bitte einen Benutzernamen angeben.", "error"));
			$vars_valid = false;
		}
		if(empty($_POST['pw']))
		{
			$this->log->add_log_entry(new log_entry("Bitte ein Passwort eingeben.", "error"));
			$vars_valid = false;
		}
		if(empty($_POST['enter_pw']))
		{
			$this->log->add_log_entry(new log_entry("Bitte das Passwort best&auml;tigen.", "error"));
			$vars_valid = false;
		}
		if($vars_valid)
		{
			if($_POST["pw"] == $_POST["enter_pw"])
			{
				return true;
			}
			$this->log->add_log_entry(new log_entry("Passworteingaben stimmen nicht &uuml;berein.", "error"));
			return false;
		}
		return false;
	}

}
?>